import React from 'react';
import { Switch, Route } from "react-router"
import { withRouter } from "react-router-dom"
import routerConfig from "./routerConfig"
import Error404Page from "../pages/Error404"

import { CSSTransition, TransitionGroup } from 'react-transition-group';
import './index.scss'

const DEFAULT_SCENE_CONFIG = {
  enter: 'from-right',
  exit: 'to-right'
};

const getSceneConfig = location => {
  const matchedRoute = routerConfig.find(config => new RegExp(`^${config.path}$`).test(location.pathname));
  return (matchedRoute && matchedRoute.sceneConfig) || DEFAULT_SCENE_CONFIG;
};

let oldLocation = null;

const Router = withRouter(({ location, history }) => {

  // 转场动画应该都是采用当前页面的sceneConfig，所以：
  // push操作时，用新location匹配的路由sceneConfig
  // pop操作时，用旧location匹配的路由sceneConfig
  let classNames = '';
  if (history.action === 'PUSH') {
    classNames = 'forward-' + getSceneConfig(location).enter;
  } else if (history.action === 'POP' && oldLocation) {
    classNames = 'back-' + getSceneConfig(oldLocation).exit;
  }

  // 更新旧location
  oldLocation = location;

  return (
    <TransitionGroup
      className={'router-wrapper'}
      childFactory={child => React.cloneElement(child, { classNames })}
    >
      <CSSTransition timeout={200} key={location.pathname}>
        <Switch location={location}>
          {routerConfig && routerConfig.map((config, index) => <Route exact key={index} path={config.path} render={(props) => {
            document.title = config.title
				    return <config.component {...props}></config.component>
          }} />)}
          <Route component={Error404Page} />
        </Switch>
      </CSSTransition>
    </TransitionGroup>

  );
})

export default Router
